import { firstUpperCase, isUpperCase } from './generator-html';

export const generatorInitForm = (widgetList: any) => {
  return `

initForm() {
  this.validateForm = this.fb.group({
    ${createInitForm(widgetList)}
  });
}`;
};

export const generatorUploadFun = (widgetList: any) => {
  let temp = '';
  widgetList.map(item => {
    if (item.name === 'Upload') {
      temp += generatorDeleteFileFun(item);
      temp += generatorGetUploadInfo(item);
    }
    if (item.name === 'Row') {
      if (item.children) {
        item.children.map(child => {
          if (child.name === 'Upload') {
            temp += generatorDeleteFileFun(child);
            temp += generatorGetUploadInfo(child);
          }
        });
      }
    }
  });
  return temp;
};

/**
 * 生成删除文件方法
 * @param data data
 */
const generatorDeleteFileFun = (data: any) => {
  return `
${data.field}DeleteFile = (file: UploadField) => {
  this.${data.field}FileList.forEach((item, i) => {
    if (item.uid === file.uid) {
      this.${data.field}FileList.splice(index, 1);
    }
  });
}
  `;
};


/**
 * 生成获取上传信息方法
 * @param data data
 */
const generatorGetUploadInfo = (data: any) => {
  return `
${data.field}GetUploadInfo(event) {
  const { file, fileList, type } = event;
  if (type === 'success') {
    if (file.response.status === StatusEnum.SUCCESS) {
      fileList.forEach(item => {
        if (item.response) {
          const datas = item.response.datas;
          item.uid = datas.id;
          item.url = this.linkInfo + 'source/view/' + datas.moduleName + '/' + datas.fileNewName;
        }
      });
      this.${data.field}FileList = fileList;
    } else {
      this.message.warning('文件上传失败,请移除文件!');
    }
  }
}
  `;
};

const createInitForm = (widgetList: any) => {
  let formStr = '';
  const len = widgetList.length;
  widgetList.map((item: any, i) => {
    if (item.children) {
      const fieldTemp = item.children.map((child: any) => {
        if (child.name === 'Upload') {
          return '';
        } else {
          return `${child.field}: [this.formMap.${child.field}, [${child.required ? 'Validators.required' : ''}]]`;
        }
      });
      // 删除空值
      fieldTemp.forEach((ele: string, index: number) => {
        if (ele === '') {
          fieldTemp.splice(index, 1);
        }
      });
      formStr += fieldTemp.join(',\n    ');
    } else {
      if (item.name !== 'Table' && item.name !== 'Upload') {
        formStr += `${item.field}: [this.formMap.${item.field}, [${item.required ? 'Validators.required' : ''}]],`;
        formStr += (i < len - 1 ? '\n     ' : '');
        // 删除最后一个逗号
        formStr = formStr.slice(0, -1);
      }
    }
  });
  return formStr;
};

export const initTsTemp = (widgetList: any) => {
  let temp = `
validateForm: FormGroup;
formMap: FormMap = new FormMap();`;
  if (hasUpload(widgetList)) {
    temp += '\nuploadUrl = `${SERVERS_NAME.UPLOAD_URL}`;\n' +
      'headerInfo = StorageUtil.getFileHeader();\n' +
      'linkInfo = `${HTTP_BASE_URL}${SERVERS_NAME.SECURITY_SERVER}`;\n';
  }
  widgetList.map((item: any) => {
    if (['Cascader', 'TreeSelect'].includes(item.name)) {
      temp += `
${item.field}List = [];`;
    }
    if (['CheckboxGroup', 'RadioGroup', 'Select'].includes(item.name)) {
      temp += `
${item.field}List = ${JSON.stringify(item.options, null, 2)};`;
    }
    if (['Upload'].includes(item.name)) {
      temp += `
${item.field}FileList = [];
      `;
    }
    if (item.name === 'Row') {
      if (item.children) {
        item.children.map((ele: any) => {
          if (['Cascader', 'TreeSelect'].includes(ele.name)) {
            temp += `
${ele.field}List = [];`;
          }
          if (['CheckboxGroup', 'RadioGroup', 'Select'].includes(ele.name)) {
            temp += `
${ele.field}List = ${JSON.stringify(ele.options, null, 2)};`;
          }
          if (['Upload'].includes(ele.name)) {
            temp += `
${ele.field}FileList = [];
      `;
          }
        });
      }
    }
  });
  return temp;
};

export const initTsTable = (widgetList: any) => {
  let temp = '';
  widgetList.map((item: any) => {
    if (item.name === 'Table') {
      temp += `
${isUpperCase(item, 'serviceMap')}: ServiceMap = {
  http: this.http,
  message: this.message,
  that: this
};
${isUpperCase(item, 'crud')} = new Crud(
  this.${isUpperCase(item, 'serviceMap')},
  ${firstUpperCase(item.field)}SearchParams
);
${generatorFieldListByColumns(item.columns)}`;
    }
  });
  return temp;
};

export const generatorFormMapClass = (widgetList: any) => {
  return `
class FormMap {
  ${widgetList.map((item: any) => {
    if (item.children) {
      return item.children.map((child: any) => {
        let type = '';
        if (child.name === 'Upload') {
          return '';
        }
        if (['CheckboxGroup'].includes(child.name) ||
          (['TreeSelect'].includes(child.name) && child.checkable) ||
          (['Select'].includes(child.name) && child.mode !== 'default')) {
          type = '[]';
        } else if (['InputNumber'].includes(child.name)) {
          type = 'number';
        } else if (['Switch'].includes(child.name)) {
          type = 'boolean';
        } else {
          type = 'string';
        }
        return `${child.field}: ${type};`;
      }).join('\n  ');
    } else {
      if (item.name === 'Table' || item.name === 'Upload') {
        return '';
      }
      let type = '';
      if (['CheckboxGroup'].includes(item.name) ||
        (['TreeSelect'].includes(item.name) && item.checkable) ||
        (['Select'].includes(item.name) && item.mode !== 'default')) {
        type = '[]';
      } else if (['InputNumber'].includes(item.name)) {
        type = 'number';
      } else if (['Switch'].includes(item.name)) {
        type = 'boolean';
      } else {
        type = 'string';
      }
      return `${item.field}: ${type};`;
    }
  }).join('\n  ')}
}
    `;
};

export const generatorSearchParams = (widgetList: any) => {
  let temp = '';
  widgetList.map((item: any) => {
    if (item.name === 'Table') {
      temp += `
class ${firstUpperCase(item.field)}SearchParams { ${generatorSearchParamsFieldByColumns(item.columns)}
}`;
    }
  });
  return temp;
};

export const generatorSearchParamsFieldByColumns = (columns: any) => {
  let temp = `\n`;
  columns.map(item => {
    if (item.showFilter) {
      temp += `  ${item.field}: number;\n`;
    }
    if (item.customFilter) {
      temp += `  ${item.field}: string;\n`;
    }
  });
  return temp;
};


export const generatorFieldListByColumns = (columns: any) => {
  let temp = '';
  columns.map(item => {
    if (item.showFilter) {
      temp += `
${item.field}List = [];`;
    }
  });
  return temp;
};


export const generatorEChartFun = (data: any) => {
  return `
renderChart() {
  const compChart = echarts.init(document.querySelector('.chart-comp'));
  const option = ${JSON.stringify(data, null, 4)};
  compChart.setOption(option);
}
`;
};


/**
 * 判断是否有上传组件
 * @param widgetList 数据
 */
export const hasUpload = (widgetList: any) => {
  let flag = false;
  widgetList.map(item => {
    if (item.name === 'Upload') {
      flag = true;
    }
    if (item.name === 'Row') {
      if (item.children) {
        item.children.map(ele => {
          if (ele.name === 'Upload') {
            flag = true;
          }
        });
      }
    }
  });
  return flag;
};
